package com.example.springboot.controller.redis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/2 15:18
 */
@RestController
@RequestMapping("/czk/wechat")
@Api(tags = "微信步数排行榜管理")
public class WechatStep {
    @Autowired
    private RedisTemplate redisTemplate;
    ThreadLocalRandom random = ThreadLocalRandom.current();

    @GetMapping("/init/{username}/{num}")
    @ApiOperation(value = "初始化好友步数")
    public String init(@PathVariable String username, @PathVariable Integer num) {

        // 初始化
        String key = "step:" + username;
        for (Integer i = 0; i < num; i++) {
            String friend = "czk-" + i;
            redisTemplate.opsForZSet().add(key, friend, random.nextDouble());
            // 存储点赞数
            // key=自己用户名+好友用户名
            String likeKey = username + ":" + friend;
            saveStepInformation(likeKey, friend);
        }
        return "初始化成功";
    }

    @ApiOperation(value = "步数点赞")
    @GetMapping("/add/like/{username}/{friendName}")
    public String addLike(@PathVariable String username, @PathVariable String friendName) {
        redisTemplate.opsForHash().increment(username + ":" + friendName, "likeNum", 1);
        return "点赞成功";
    }

    @ApiOperation(value = "取消点赞")
    @GetMapping("/cancel/like/{username}/{friendName}")
    public String cancelLike(@PathVariable String username, @PathVariable String friendName) {
        redisTemplate.opsForHash().increment(username + ":" + friendName, "likeNum", -1);
        return "点赞成功";
    }

    @ApiOperation(value = "步数top5")
    @GetMapping("/top5/{username}")
    public Set<String> top5(@PathVariable String username) {
        // 拿到好友用户步数前五名
        // zset的逆序取值
        Set range = redisTemplate.opsForZSet().reverseRange("step:" + username, 0, 4);
        return range;
    }

    /**
     * 利用hash存储好友信息
     * key为用户名称加好友名称
     * 可以包括点赞数，头像这些
     *
     * @param likeKey
     * @param friendName
     */
    private void saveStepInformation(String likeKey, String friendName) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        // 存储信息
        hashOperations.put(likeKey, "name", friendName);
        hashOperations.put(likeKey, "header", friendName);
        hashOperations.put(likeKey, "likeNum", random.nextInt(20));
    }

}
